<?php

namespace app\models\order;

use app\models\AdminSupplier;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use Yii;

/**
 * This is the model class for table "order".
 *
 * @property int $id
 * @property int $user_id
 * @property string $sn
 * @property string $create_time
 * @property string $update_time
 * @property int $status
 * @property int $total_quantity 总数量
 * @property float $total_price 总金额
 * @property float $total_freight 总运费
 * @property float $total_pay 实际需要支付金额: $total_pay = $total_score + $total_freight + $total_price;
 * @property float $use_balance 使用余额支付
 * @property float $use_score 使用积分支付
 * @property float $use_money 使用现金支付
 * @property float $use_platform_ticket 使用平台券支付
 * @property string $pay_type_name 支付方式文本说明
 * @property int $pay_type 支付方式 1 正常, 2 后台
 * @property int $is_group 是否为拼团订单
 * @property int $user_address 收货地址
 * @property string $request_params 收货地址
 * @property int $return_sale 是否返销售(业绩)奖
 * @property int $supplier_id
 * @property int $is_store 是否进云仓, 1 进, 0 发货
 * @property int $store_box 进云仓数量
 * @property int $is_extract 上否为提货订单
 * @property int $is_platform 是否从平台出, 1 平台, 0 上级
 * @property int $leader 上级领导 (可能货进他出, 如果库存足够)
 * @property int $add_84
 */
class Order extends \yii\db\ActiveRecord
{
    /**
     * status list
     * @var int[]
     */
    public static $statusMapping = [
        'ALL' => -1,            // 全部
        'NON_PAYMENT' => 0,     // 待支付
        'PAID' => 1,            // 已支付(待发货)
        'WAIT_RECEIVING' => 2,  // 待收货
        'RECEIVED' => 3,        // 已收货(待评价)
        'SERVICE' => 4,         // 售后
        'CANCEL' => 5,          // 取消
        'FINISH' => 10,         // 完成
        'DELETE' => -99,        // 删除
        'REFUND' => 6,          // 已退货
    ];

    /**
     * status display list
     * @var int[]
     */
    public static $statusMappingDisplay = [
        '全部' => -1,
        '待支付' => 0,
        '待发货' => 1,
        '待收货' => 2,
        '待评价' => 3,
        '售后' => 4,
        '已取消' => 5,
        '已完成' => 10,
        // '删除' => -99,
        '已退货' => 6,
    ];

    /**
     * Status list
     *
     * @return array
     */
    public static function statusList()
    {
        $list = [];
        foreach (self::$statusMappingDisplay as $key => $value) {
            $list[] = [
                'label' => $key,
                'value' => $value
            ];
        }

        return $list;
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'order';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'status', 'total_quantity', 'pay_type'], 'integer'],
            [['create_time', 'update_time'], 'safe'],
            [['total_price', 'total_freight', 'total_pay', 'use_balance', 'use_score', 'use_money', 'use_platform_ticket'], 'number'],
            [['total_pay'], 'required'],
            [['sn', 'pay_type_name'], 'string', 'max' => 255],

            // is group order
            [['is_group'], 'safe'],

            [['user_address'], 'safe'],

            [['request_params'], 'safe'],

            // sale
            [['return_sale'], 'safe'],

            // offline
            [['offline_ok', 'remark', 'log'], 'safe'],

            [['supplier_id'], 'safe'],


            [['is_store', 'store_box', 'is_extract', 'is_platform', 'leader', 'add_84'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'sn' => 'Sn',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'status' => 'Status',
            'total_quantity' => 'Total Quantity',
            'total_price' => 'Total Price',
            'total_freight' => 'Total Freight',
            'total_pay' => 'Total Pay',
            'use_balance' => 'Use Balance',
            'use_score' => 'Use Score',
            'use_money' => 'Use Money',
            'use_platform_ticket' => 'Use Platform Ticket',
            'pay_type_name' => 'Pay Type Name',
            'pay_type' => 'Pay Type',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public static function generateSn()
    {
        do {
            $sn = date('YmdHis') . mt_rand(10000, 99999);
        } while(self::findOne(['sn' => $sn]));

        return $sn;
    }

    public function getItem()
    {
        return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
    }

    public function getAddress()
    {
        return $this->hasOne(UserAddress::class, ['id' => 'user_address']);
    }

    public function getUser()
    {
        return $this->hasOne(User::class, ['id' => 'user_id'])
            ->select(['id', 'mobile', 'nickname', 'avatar', 'base64Image']);
    }

    public function getCommission()
    {
        return $this->hasMany(UserCommission::class, ['order_id' => 'id'])->limit(1000);
    }

    // 供应商(只显示名称, id)
    public function getSupplier()
    {
        return $this->hasOne(AdminSupplier::class, ['id' => 'supplier_id'])
            ->select(['name', 'id']);
    }
}
